package com.common.www.controller.tabulation;


import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.tabulation.AllTabulation;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.tabulation.AllTabulationService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/allTabulation"})
@Api(tags = "MGT 后台全系清单管理")
public class MGTAllTabulationController extends DefaultCrudController<AllTabulation, Long> {

    @Autowired
    private AllTabulationService allTabulationService;

    protected IBaseService<AllTabulation, Long> getService() {
        return allTabulationService;
    }


    @ApiOperation("保存单个全系清单数据")
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(@RequestBody AllTabulation allTabulation) {
        if (allTabulation.getId() != null) {
            // 更新操作
            AllTabulation existingTabulation = allTabulationService.getByIdLogic(allTabulation.getId());
            if (existingTabulation == null) {
                throw new ServiceException("未找到目标对象");
            }
            // 复制属性到现有对象，排除ID字段
            BeanUtils.copyProperties(allTabulation, existingTabulation, "id");
            // 保存现有对象
            allTabulationService.save(existingTabulation);
            return R.ok(existingTabulation);
        } else {
            // 新增操作，直接保存传入的对象
            allTabulationService.save(allTabulation);
            return R.ok(allTabulation);
        }
    }


    @ApiOperation("批量删除单个供货清单数据（逻辑删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids) {
        if (ParamsUtils.isInputEmpty(ids)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        allTabulationService.deleteByIdsLogic(ids);
        return R.ok();
    }


    @ApiOperation(value = "导入全系清单", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importQxqd", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importQxqd(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, file.getOriginalFilename());
        List<AllTabulation> listImport = allTabulationService.importSimulate(workbook);
        //整理listImport的数据格式
        List<AllTabulation> listArrange = new ArrayList<>();

        Integer lastNonNullOriginalFenLei = null;
        for (AllTabulation listObj : listImport) {
            Integer originalFenLei = listObj.getFenLei();
            if (originalFenLei != null) {
                lastNonNullOriginalFenLei = originalFenLei;
            } else {
                if (lastNonNullOriginalFenLei != null) {
                    listObj.setFenLei(lastNonNullOriginalFenLei);
                }
            }
//            if (StringUtils.isNotEmpty(listObj.getName())) {
                listArrange.add(listObj);
//            }
        }
        //上传之前先删除全部
        HashMap hashMap = new HashMap();
        hashMap.put("flag", 1);
        List<AllTabulation> allTabulationList = allTabulationService.queryToList(hashMap,null);
        allTabulationService.delete(allTabulationList);
        allTabulationService.save(listArrange);

        return R.ok();
    }


    @ApiOperation("导出全系清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportQxqd", method = RequestMethod.GET)
    public Result exportQxqd() {

        String fileName = "全系清单-全导出";
        XSSFWorkbook workbook = allTabulationService.exportQxqd();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "(全系清单).xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


}


